<template>
  <view>
    <loader ref="c-loader" @ready="onLoader"></loader>
    <view class="vn" :class="{ 'vnShow' : isLoad }">
      <music ref="c-music" v-model="music.isStart" :state="music"></music>
      <view class="questionMod" :style="style" @touchmove.prevent="noop" v-if="step == 1 || step == 2">
        <view class="errorMsg"></view>
        <view class="game-dir">请向左滑动</view>
        <view class="cjMp3" :class="{ 'on' : music.isStart }" @tap="onToggle"></view>
        <view class="qm-item">
          <view class="qm-full qmPage1">
            <view class="qp-bg qm-full"></view>
            <view class="qp-logo"></view>
            <view class="qp-btn" @tap="onQuestion" v-if="!is_snap"></view>
          </view>
        </view>
        <view class="qm-item qm-full qm-step2" :class="{ 'animated slideInRight' : step == 2 }">
          <view class="qm-person"></view>
          <view class="qm-scroll" @touchstart="onStart" @touchmove="onMove" @touchend="onEnd" :style="moveStyle">
            <view class="qmPage2">
              <!--view class="qp-item" v-for="(item,index) in list" :style="item.style"></view-->
            </view>
          </view>
        </view>
        <block v-if="step == 2">
          <view class="qm-full qmQuestion" :class="{ 'show' : isQ > -1}" v-if="!isEnd">
            <view class="qq-inner" :class="{ 'show' : isQ > 0 }">
              <view class="qq-qs" v-if="isQ == 1">
                <view class="qq-no">第{{ currentQ.no }}题</view>
                <view class="qq-q" v-html="currentQ.q"></view>
                <view class="qq-items">
                  <view class="qq-item" :class="[{ 'on' : item.selected },'style' + currentQ.style,'cls' + (currentQ.cls || 0) ]" v-for="(item,index) in currentQ.items" @tap="onSelect" :key="index" :data-index="index"><view class="qq-index">{{ index + 1 }}</view><view class="qq-text">{{ item.name }}</view></view>
                </view>
                <view class="qq-btn" @tap="onAnswer"></view>
              </view>
              <view class="qq-answer animated fadeIn" v-if="isQ == 2">
                <view class="qq-resultPic" :class="{ 'wrong' : answer.status == 2 }"></view>
                <view class="qq-resultBtn" @tap="onTip"></view>
              </view>
              <view class="qq-tip" v-if="isQ == 3">
                <view class="qq-tip-1" @touchmove.stop="noop">
                  <view class="qq-tip-content" :class="['style' + currentQ.style]">
                    <view class="qq-tip-content-1">文明Tips</view>
                    <div class="qq-tip-content-2" v-html="currentQ.tipHtml" v-if="currentQ.tipHtml"></div>
                    <div class="qq-tip-content-2" v-html="currentQ.tip"></div>
                    <view v-if="currentQ.imgsScroll" class="qq-tip-content-3 hasScroll">
                      <customScroll v-if="currentQ.imgs && currentQ.imgs.length" :from="currentQ.imgsScroll">
                        <div class="qq-tip-content-inner">
                          <div class="qq-tip-content-img" :class="['s' + currentQ.imgStyle ]" v-for="(item,index) in currentQ.imgs" :key="index">
                            <img class="blockImg" :src="imageFormat(item)"></img>
                          </div>
                        </div>
                      </customScroll>
                    </view>
                    <block v-else>
                      <view class="qq-tip-content-3" v-if="currentQ.imgs && currentQ.imgs.length">
                        <view class="qq-tip-content-inner">
                          <view class="qq-tip-content-img" :class="['s' + currentQ.imgStyle ]" v-for="(item,index) in currentQ.imgs" :key="index">
                            <img class="blockImg" :src="imageFormat(item)"></img>
                          </view>
                        </view>
                      </view>
                    </block>
                  </view>
                  <view class="qq-tip-2" @tap="onNext"></view>
                </view>
              </view>
            </view>
          </view>
          <view class="qm-full qmEnd animated fadeIn show" v-if="isEnd">
            <view class="qe-inner" v-if="score.status == 1">
              <view class="qe-inner2">
                <view class="qe-t1">您的成绩为：{{ score.num }}分</view>
                <view class="qe-t2">分数达到90分，可获得一次抽奖机会<br/>活动期间每人仅有一次中奖机会</view>
                <view class="qe-t3" @tap="goCj"></view>
              </view>
              <view class="qe-t4"><span @tap="onIndex">返回首页</span></view>
            </view>
            <view class="qe-inner" v-if="score.status == 2">
              <view class="qe-inner3">
                <view class="qe-q1">您的成绩为：{{ score.num }}分</view>
                <view class="qe-t2">成绩必须高于90分<br/>才能抽奖</view>
                <view class="qe-q3" @tap="onAgain"></view>
              </view>
            </view>
          </view>
          <view class="qm-full qmCj animated fadeIn show" v-if="isCj">
            <view class="qe-inner" v-if="cj.status == 1">
              <view class="qe-inner2">
                <view class="qe-btn" @tap="onCj"></view>
              </view>
            </view>
            <view class="qe-inner" v-if="cj.status == 2">
              <view class="qe-inner2 s2">
                <view class="qe-t1">恭喜您获得<span class="qe-num">{{ cj.num }}</span>元</view>
                <view class="qe-t2">红包会自动发送到微信钱包</view>
                <view class="qe-t3" @tap="onInvite"></view>
              </view>
            </view>
            <view class="qe-inner" v-if="cj.status == 3">
              <view class="qe-inner3">
                <view class="qe-out"></view>
                <view class="qe-out-text">{{ cj.msg }}</view>
                <view class="qe-out-btn" @tap="onIndex"></view>
              </view>
            </view>
            <view class="qe-inner" v-if="cj.status == 4">
              <view class="qe-inner3">
                <view class="qe-out"></view>
                <view class="qe-out-text">{{ cj.msg }}</view>
                <view class="qe-out-btn" @tap="onIndex"></view>
              </view>
            </view>
          </view>
        </block>
      </view>
      <view id="qmShare"></view>
      <view class="qm-item" v-if="step == 3 && url">
        <div class="qmShareOut animated fadeIn">
          <img :src="url"/>
          <div class="qs-text">长按保存海报</div>
        </div>
      </view>
    </view>
    <view class="lock"></view>
  </view>
</template>
<script>
import zrender from '@/libs/zrender.min.js'
import { imgToBase64 } from '@/utils/imgToBase64.js'
import music from '@/components/music.vue'
import loader from '@/components/loader.vue'
import q from './q.js'
import app from '@/g.js'
import customScroll from '../components/customScroll.vue'
import Api from '../class/Api.class.js'
import qrcode from 'qrcode'
export default {
  components : {
    music,
    loader,
    customScroll
  },
  data() {
    return {
      isLoad : false,
      step : 1,
      style : {},
      url : '',
      music : {
        isStart : true,
        title : `“井”然有序文明城`
      },
      ...q,
      isQ : -1,
      isEnd : false,
      isCj : false,
      canMove : true,
      start : {},
      moveStyle : {},
      nowDy : 0,
      lastDy : 0,
      nowIndex : 0,
      systemInfo : {},
      answer : {
        status : 1,
      },
      score : {
        status : 1,
        num : 0,
      },
      cj : {
        status : 1,
        num : 9.9,
        msg : '',
      },
      is_snap : false,
      isAuth : false,
    }
  },
  computed : {
    nowCheckY(){
      let item = this.list[this.nowIndex];
      return item.x - 100 - (item.dx || 0);
    },
    currentQ(){
      let item = this.list[this.nowIndex];
      return item.question;
    },
  },
  onLoad(options) {
    this.is_snap = !!options.is_snap;
    uni.setStorageSync('options',options);
    uni.setNavigationBarTitle({
      title : '“井”然有序文明城'
    })


    let systemInfo = uni.getSystemInfoSync();
    let { windowWidth,windowHeight } = systemInfo;
    this.systemInfo = systemInfo;
    this.style = {
      height : windowWidth + 'px',
      width : windowHeight + 'px',
      //transform:`translate(-50%,-50%) rotate(90deg)`
      transform:`translate(-50%,-50%) rotate(90deg)`
    }
    /*
    this.style = {
      height : windowHeight + 'px',
      width : windowWidth + 'px',
      //transform:`translate(-50%,-50%) rotate(90deg)`
      transform:`translate(-50%,-50%)`
    }
    */

    this.init();

    app.wxReady$.then(res => {
      this.wx = res;
      app.api.onShareH5(res);
    });
    this.checkWeChatCode();
  },
  methods: {
    checkLocation(){
      return this.getLocation().then(loc => {
        //这里判断是否在条件内
        return app.api.checkLocation(loc).then(res => {
          if(res.code == 1){
            this.showMsg(res.msg);
            return Promise.reject();
          }else{
            uni.setStorageSync('location',loc);
            return res;
          }
        })
      })
    },
    getLocation(){
      return new Promise(resolve => {
        let { wx } = this;
        wx.getLocation({
          type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            resolve({
              lat : latitude,
              lng : longitude
            })
          },
          fail(res){
            resolve({});
          }
        });
      })
    },
    onLoader(){
      this.isLoad = true;
      this.$nextTick(res => {
        uni.showToast({
          title : `请横屏查看本页`,
          icon : 'none'
        })
      })
    },
    calResult(){
      let { list } = this;
      let score = 0;
      list.forEach(res => {
        let flag = res.question.items.filter(res => {
          return res.isR
        }).every(res => {
          return res.selected
        })
        if(flag){
          score += 10;
        }
      });


      this.score.num = score;
      if(score < 90){
        this.score.status = 2;
      }else{
        this.score.status = 1;
      }

    },
    noop(){},
    init(){
      let list = this.list;
      this.list = list.map(res => {
        let { x,w,h,url } = res;
        let { windowWidth } = this.systemInfo;
        x = windowWidth / 750 * x;
        res.style = {
          width : w + 'rpx',
          height : '750rpx',
          background : `url(${ url }) 0 bottom / 100% auto no-repeat`,
          transform : `translate(${ x }px,0)`,
        }
        res.x = x;
        return res;
      })
    },
    onStart(e){
      if(this.canMove){
        this.start = e.touches[0];
      }
    },
    onMove(e){
      if(this.canMove){
        let now = e.touches[0];
        let { start } = this;
        let sy = start.clientY;
        let ey = now.clientY;
        let dy = ey - sy;
        if(dy > this.lastDy) return;

        this.lastDy = dy;
        let y = dy + this.nowDy;
        if(Math.abs(y) > this.nowCheckY){
          this.isQ = 1;
          this.canMove = false;
        }
        this.moveStyle = {
          transform : `translateX(${ y }px)`
        }
      }
    },
    onEnd(e){
      if(this.canMove){
        this.nowDy = this.nowDy + this.lastDy;
        this.lastDy = 0;
      }
    },
    onAnswer(){
      let hasSelect = this.checkSelect();
      if(hasSelect){
        let flag = this.checkAnswer();
        if(flag){
          this.answer.status = 1;
        }else{
          this.answer.status = 2;
        }
        this.isQ = 2;
      }else{
        this.showMsg(`请选择选项`);
      }
    },
    showDir(){
      $('.game-dir').show();
      setTimeout(() => {
        $('.game-dir').hide();
      },3e3);
    },
    showMsg(text){
      $('.errorMsg').html(text).show();
      setTimeout(() => {
        $('.errorMsg').hide();
      },2e3);
    },
    showLoading(){
      $('.errorMsg').html(`海报生成中`).show();
    },
    hideLoading(){
      $('.errorMsg').hide();
    },
    checkSelect(){
      let currentQ = this.currentQ;
      return currentQ.items.filter(res => {
        return res.selected;
      }).length > 0;
    },
    checkAnswer(){
      let currentQ = this.currentQ;
      let { mul } = currentQ;
      return currentQ.items.filter(res => {
        return res.isR;
      }).every(res => {
        return res.selected;
      })
    },
    onTip(){
      this.isQ = 3;
    },
    onNext(){
      this.nowIndex++;
      if(this.nowIndex == this.list.length){
        this.isQ = -1;
        this.isEnd = true;
        this.canMove = false;
        this.calResult();
      }else{
        this.isQ = 0;
        setTimeout(() => {
          this.isQ = -1;
        },300);
        this.showDir();
        this.canMove = true;
      }
    },
    onIndex(){
      this.isEnd = false;
      this.isQ = -1;
      this.step = 1;
    },
    //去抽奖
    goCj(){
      //this.showMsg('活动已结束');
      //return;
      this.isEnd = false;
      this.isCj = true;
    },
    //抽奖后台
    onCj(){
      let openid = uni.getStorageSync('openid');
      let token = uni.getStorageSync('token');
      let location = uni.getStorageSync('location');
      $('.errorMsg').html(`抽奖中，请稍等`).show();
      Api.lottery({
        openid,
        token,
        lat : location.lat,
        lng : location.lng,
      }).then(res => {
        $('.errorMsg').hide();
        let { code } = res;
        let status = 1;
        if(code == 0){
          status = 2;
        }else if(code == 2){
          status = 3;
        }else{
          status = 4;
        }
        this.cj.num = res.money;
        this.cj.msg = res.msg;
        this.cj.status = status;
      })
    },
    onQuestion(){
      /*
      let openid = uni.getStorageSync('openid');
      if(openid){
        this.step = 2;
        this.showDir();
      }else{
        */
        this.checkLocation().then(res => {
          this.wxLogin();
        })
      //}
    },
    createPoster(){
      let u1 = 'https://s.hangjiayun.com/zhuanti/question/images/share.png';
      //let u2 = 'https://s.hangjiayun.com/zhuanti/question/images/ercode.png';
      return new Promise(resolve => {
        imgToBase64([{
          url : u1
        }]).then(res => {
          this.createCode().then(code => {
            let main = zrender.init(document.getElementById('qmShare'),{
              width : 750,
              height : 1458
            });

            let bg = new zrender.Image({
              style : {
                image : res[0],
                width : 750,
                height : 1458
              }
            })

            let ercode = new zrender.Image({
              style : {
                //image : res[1],
                image : code,
                width : 170,
                height : 170,
              },
              position : [290,794]
            })

            main.add(bg);
            main.add(ercode);

            setTimeout(() => {
              let canvas = main.painter._layers[0].dom;
              let url = canvas.toDataURL('image/jpeg',1);
              this.url = url;
              resolve();
            },300);
          })

        })
      })
    },
    onToggle(){
      let c = this.$refs['c-music'];
      c.onToggle();
    },
    createCode(){
      return new Promise(resolve => {
        qrcode.toDataURL("https://hongbao.hangjiayun.net/answer/index",{
          width: 170,
          margin : 0,
          color : {
            dark: '#000',
            light: '#fff'
          }
        }, (err, res) => {
          resolve(res);
        });
      })
    },
    onInvite(){
      this.showLoading();
      this.isCj = false;
      this.$nextTick(res => {
        this.createPoster().then(res => {
          this.step = 3;
          this.hideLoading();
        })
      })
    },
    onSelect(e){
      const { index } = e.currentTarget.dataset;
      let item = this.list[this.nowIndex].question;
      let { mul } = item;
      let now = item.items[index];
      if(mul){
        now.selected = !now.selected;
      }else{
        item.items.forEach(res => res.selected = false);
        now.selected = true;
      }
      this.$forceUpdate();
    },
    reset(){
      this.list.forEach(res => {
        res.question.items.forEach(res => res.selected = false);
      });
      this.step = 2;
      this.isQ = -1;
      this.isEnd = false;
      this.isCj = false;
      this.nowIndex = 0;
      this.nowDy = 0;
      this.lastDy = 0;
      this.canMove = true;
      this.moveStyle = {};
    },
    onAgain(){
      this.reset();
      this.step = 1;
    },
    onIndex(){
      this.reset();
      this.step = 1;
    },
    // 重定向回来本页面检查有没有code
    checkWeChatCode() {
      let code = this.getUrlCode('code');
      if(code) {
        this.handleToLogin(code)
      }
    },
    // 正则匹配请求地址中的参数函数
    getUrlCode(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||[, ''])[1].replace(/\+/g, '%20')) || null
    },
    // 看地址中有没有code参数,如果没有code参数的话则请求微信官方的接口并获取包含code的回调链接
    wxLogin() {
        //用于退出登录回来不会再调一次授权登录
        const appID = 'wxa776cdb9fbdb7bb9';  //公众号appID
        const callBack = 'https://hongbao.hangjiayun.net/h5/#/'; //回调地址 就是你的完整地址登录页
                    
        //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
        window.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
                        appID + '&redirect_uri=' + encodeURIComponent(callBack) +
                        '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect');
    },
    handleToLogin(code){
      //这里如果解出openid那么就直接进入答题，否则不用管
      let location = uni.getStorageSync('location');
      return app.api.getOpenidByCode({
        code,
        lng : location.lng,
        lat : location.lat,
      }).then(res => {
        let openid = res.openid
        let token = res.token;
        if(openid && token){
          uni.setStorageSync('openid',openid);
          uni.setStorageSync('token',token);
          this.step = 2;
          this.showDir();
        }else{
          this.showMsg(`微信授权失败`);
        }
      })
    },
  }
}
</script>
<style>
</style>
